from math import *
from agent import *
from time import time
import copy
import pickle

class action_wrapper(object):
	def __init__(self,action_name,logger):
		self.action_name=action_name
		self.logger=logger
	def call(self,*args):
		self.logger(self.action_name,*args)

class agent_logger(agent):
	def __init__(self,actions,senses,agent_num=None,fitness_function=None):
		agent.__init__(self,actions,senses,agent_num,fitness_function)
		self.cmd_log=[] # Stored in the format (a list of the following) [{action_name:action_parameter_list},{sense1_name:sense1_parameter_list,sense2_name:sense2_parameter_list...}]
		self.real_actions=actions
		self.actions={}
		self.log_enabled=True

		# Instrument actions
		for action in self.real_actions.iterkeys():
			print(action)
			wrapper=action_wrapper(action,self.log)
			self.actions[action]=wrapper.call
	def think(self):
		return
	def toggle_logging(self):
		self.log_enabled=not self.log_enabled
		print('LogEnabled:'+str(self.log_enabled))
	def log(self,action_name,*args):
		print('Logged '+action_name)
		print(args)
		args=copy.deepcopy(args)
		sense_out={}
		action_in={action_name:args}
		for sense in self.senses.iterkeys():
			sense_out[sense]=self.senses[sense]()
		if self.log_enabled:
			self.cmd_log.append([action_in,sense_out])
		self.real_actions[action_name](*copy.deepcopy(args))
	def save(self):
		f=file(str(time())+'.txt','w')
		pickle.dump(self.cmd_log,f)
		f.close()
